package com.huluobo.a2202mvvm_im_douyindemo.live;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.huluobo.a2202mvvm_im_douyindemo.R;
import com.huluobo.a2202mvvm_im_douyindemo.adapter.ChatRoomMessageAdapter;
import com.huluobo.a2202mvvm_im_douyindemo.adapter.GiftAdapter;
import com.huluobo.a2202mvvm_im_douyindemo.bean.FollowBeanResult;
import com.huluobo.a2202mvvm_im_douyindemo.bean.GiftBeanResult;
import com.huluobo.a2202mvvm_im_douyindemo.bean.Money;
import com.huluobo.a2202mvvm_im_douyindemo.bean.VideoListBeanResult;
import com.huluobo.a2202mvvm_im_douyindemo.databinding.ActivityLiveBinding;
import com.huluobo.a2202mvvm_im_douyindemo.db.AppDBUtils;
import com.huluobo.a2202mvvm_im_douyindemo.mvvmBase.BaseMVVMActivity;
import com.huluobo.a2202mvvm_im_douyindemo.mvvmBase.net.Const;
import com.huluobo.a2202mvvm_im_douyindemo.shop.ShopActivity;
import com.huluobo.a2202mvvm_im_douyindemo.utils.ImageLoader;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;

import java.util.ArrayList;
import java.util.List;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;

public class LiveActivity extends BaseMVVMActivity<ActivityLiveBinding, LiveViewModel> {

    private VideoListBeanResult.VideoListBean videoListBean;
    private GiftAdapter giftAdapter;
    private List<GiftBeanResult.GiftBean> giftBeanList = new ArrayList<>();

    private GiftBeanResult.GiftBean giftBean;
    private Money money;

    private ChatRoomMessageAdapter chatRoomMessageAdapter;

    private List<MessageEntity> messageEntitiesList = new ArrayList<>();

    @Override
    protected void initData() {
        viewModel.followAuthSuccess.observe(this, followBeanResult -> {
            ToastUtils.showLong(followBeanResult.getMessage());
            if (followBeanResult.getCode() == 200) {
                dataBinding.liveFollowBtn.setText("已关注");
                dataBinding.liveFollowBtn.setBackgroundResource(R.drawable.shape_black);
                //数据层面也需要修改为已关注,否则下次再点击还是未关注状态,无法调用到取消关注接口
                videoListBean.setGuanzhu(1);
            }
        });

        viewModel.followAuthFailed.observe(this, s -> {
            Log.i("TagA", "关注失败:" + s);
        });

        viewModel.noFollowSuccess.observe(this, followBeanResult -> {
            ToastUtils.showLong(followBeanResult.getMessage());
            if (followBeanResult.getCode() == 200) {
                dataBinding.liveFollowBtn.setText("关注");
                dataBinding.liveFollowBtn.setBackgroundResource(R.drawable.shape_red);
                //数据层面也需要修改为已关注,否则下次再点击还是未关注状态,无法调用到取消关注接口
                videoListBean.setGuanzhu(0);
            }
        });

        viewModel.noFollowFailed.observe(this, s -> {
            Log.i("TagA", "取消关注失败:" + s);
        });

        viewModel.getGiftSuccess.observe(this, giftBeanResult -> {
            if (giftBeanResult.getCode() == 200) {
                giftBeanList.clear();
                giftBeanList.addAll(giftBeanResult.getData());
                giftAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(giftBeanResult.getMessage());
            }
        });

        viewModel.getGiftFailed.observe(this, s -> {
            Log.i("TagA", "获取礼物列表失败:" + s);
        });
    }

    @Override
    protected void intiView() {
        videoListBean = (VideoListBeanResult.VideoListBean) getIntent().getSerializableExtra("videoBean");
        assert videoListBean != null;
        //设置播放器相关
        dataBinding.liveGsyPlayer.getBackButton().setVisibility(View.GONE);
        dataBinding.liveGsyPlayer.setUp(videoListBean.getVideopath(), true, "");
        //可以设置自动播放

        //设置直播基本信息
        //头像
        ImageLoader.getInstance().loadCircleImage(this, videoListBean.getHeadpath(), dataBinding.liveUserIconIv);
        //作者
        dataBinding.liveUsernameTv.setText(videoListBean.getAuthname());
        //关注状态
        dataBinding.liveFollowBtn.setText(videoListBean.getGuanzhu() == 0 ? "关注" : "已关注");
        //关注按钮的背景
        dataBinding.liveFollowBtn.setBackgroundResource(videoListBean.getGuanzhu() == 0 ? R.drawable.shape_red :
                R.drawable.shape_black);
        //喜欢数量
        dataBinding.liveLikeCountTv.setText(videoListBean.getLike_count() + "人喜欢");
        //关注点击事件
        dataBinding.liveFollowBtn.setOnClickListener(v -> {
            if (videoListBean.getGuanzhu() == 0) {
                //未关注,触发关注接口
                viewModel.followAuth(videoListBean.getAuthname());
            } else {
                //已关注,触发取消关注接口
                viewModel.noFollowAuth(videoListBean.getAuthname());
            }
        });

        //添加点赞动画资源图片
        dataBinding.liveLikeView.addLikeImages(
                R.drawable.ic_favorite_0,
                R.drawable.ic_favorite_1,
                R.drawable.ic_favorite_2,
                R.drawable.ic_favorite_3,
                R.drawable.ic_favorite_4,
                R.drawable.ic_favorite_5,
                R.drawable.ic_favorite_4,
                R.drawable.ic_favorite_3,
                R.drawable.ic_favorite_2,
                R.drawable.ic_favorite_1,
                R.drawable.ic_favorite_0
        );

        //点击点赞按钮,触发点赞动画
        dataBinding.liveLikeIv.setOnClickListener(v -> {
            dataBinding.liveLikeView.addFavor();
        });

        //单击弹出弹幕输入的布局
        dataBinding.liveDanmuIv.setOnClickListener(v -> {
            dataBinding.liveDanmuInputLl.setVisibility(View.VISIBLE);
        });

        //初始化弹幕
        initDanmuView();

        //单击发送弹幕
        dataBinding.liveDanmuSendIv.setOnClickListener(v -> {
            sendDanmu();
        });

        //打开礼物列表
        dataBinding.liveGiftIv.setOnClickListener(v -> {
            dataBinding.liveGiftLayoutCl.setVisibility(View.VISIBLE);
            viewModel.getGiftList();
            money =
                    AppDBUtils.getInstance().getMoneyDao().queryMoneyInfoByName(EMClient.getInstance().getCurrentUser());
            dataBinding.liveUserMoneyTv.setText("余额:" + money.money + "抖币");
        });

        //关闭礼物列表
        dataBinding.liveCloseTv.setOnClickListener(v -> {
            dataBinding.liveGiftLayoutCl.setVisibility(View.GONE);
        });

        //初始化礼物列表
        dataBinding.liveGiftRv.setLayoutManager(new GridLayoutManager(this, 5));
        giftAdapter = new GiftAdapter(giftBeanList);
        dataBinding.liveGiftRv.setAdapter(giftAdapter);

        giftAdapter.setOnItemClickListener((adapter, view, position) -> {
            giftBean = giftBeanList.get(position);//选中礼物的赋值
            ImageLoader.getInstance().loadImage(this, giftBean.getGiftpath(), dataBinding.liveGiftSelectIv);
            dataBinding.liveGiftNameTv.setText(giftBean.getGiftname());
        });

        //礼物发送的点击事件
        dataBinding.liveGiftSendBtn.setOnClickListener(v -> {
            sendGift();
        });

        //初始化聊天室列表
        chatRoomMessageAdapter = new ChatRoomMessageAdapter(messageEntitiesList);
        dataBinding.liveChatRoomRv.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.liveChatRoomRv.setAdapter(chatRoomMessageAdapter);

        //初始化环信聊天室
        initChatRoom();

        //聊天框发送点击事件
        dataBinding.liveChatSendIv.setOnClickListener(v -> {
//            MessageEntity messageEntity = new MessageEntity(
//                    EMClient.getInstance().getCurrentUser(),
//                    dataBinding.liveChatInputEt.getText().toString()
//            );
//            messageEntitiesList.add(messageEntity);
//            chatRoomMessageAdapter.notifyDataSetChanged();
//            dataBinding.liveChatRoomLl.setVisibility(View.GONE);

            sendChatRoomMessage(Const.CHAT_ROOM_ID, dataBinding.liveChatInputEt.getText().toString());
        });

        dataBinding.liveInputTv.setOnClickListener(v -> {
            dataBinding.liveChatRoomLl.setVisibility(View.VISIBLE);
        });

        dataBinding.liveCartIv.setOnClickListener(v -> {
            Intent intent = new Intent(this, ShopActivity.class);
            startActivity(intent);
        });

    }

    //发送环信聊天室消息
    private void sendChatRoomMessage(String chatRoomId, String content) {
        EMMessage emMessage = EMMessage.createTextSendMessage(content, chatRoomId);
        emMessage.setChatType(EMMessage.ChatType.ChatRoom);//设置聊天室消息类型
        emMessage.setBody(new EMTextMessageBody(content));//构建消息体
        EMClient.getInstance().chatManager().sendMessage(emMessage);//发送消息

        emMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                runOnUiThread(() -> {
                    MessageEntity messageEntity = new MessageEntity(
                            EMClient.getInstance().getCurrentUser(),
                            content
                    );
                    messageEntitiesList.add(messageEntity);
                    chatRoomMessageAdapter.notifyDataSetChanged();
                    dataBinding.liveChatRoomRv.scrollToPosition(messageEntitiesList.size() - 1);
                    dataBinding.liveChatInputEt.setText("");
                });
            }

            @Override
            public void onError(int code, String error) {
                ToastUtils.showLong("消息发送失败:" + error + ",code:" + code);
            }
        });
    }

    //初始化聊天室
    private void initChatRoom() {
        //给聊天室添加监听器,当接收到消息的时候,需要刷新适配器来更新数据源
        EMClient.getInstance().chatManager().addMessageListener(emMessageListener);
        //添加聊天室状态改变的监听器
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(emChatRoomChangeListener);
        //加入聊天室
        EMClient.getInstance().chatroomManager().joinChatRoom(Const.CHAT_ROOM_ID, new EMValueCallBack<EMChatRoom>() {
            @Override
            public void onSuccess(EMChatRoom value) {
                runOnUiThread(() -> {
                    MessageEntity messageEntity = new MessageEntity(
                            "系统",
                            EMClient.getInstance().getCurrentUser() + "加入直播间"
                    );
                    messageEntitiesList.add(messageEntity);
                    chatRoomMessageAdapter.notifyDataSetChanged();
                    dataBinding.liveChatRoomRv.scrollToPosition(messageEntitiesList.size() - 1);

                });
            }

            @Override
            public void onError(int error, String errorMsg) {
                Log.i("TagA", "进入聊天室失败" + errorMsg);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatroomManager().leaveChatRoom(Const.CHAT_ROOM_ID);
        EMClient.getInstance().chatroomManager().removeChatRoomListener(emChatRoomChangeListener);
        EMClient.getInstance().chatManager().removeMessageListener(emMessageListener);

    }

    //聊天室状态改变监听器,主要功能监听聊天室进入的消息
    private EMChatRoomChangeListener emChatRoomChangeListener = new EMChatRoomChangeListener() {
        @Override
        public void onChatRoomDestroyed(String roomId, String roomName) {

        }

        @Override
        public void onMemberJoined(String roomId, String participant) {
            runOnUiThread(() -> {
                MessageEntity messageEntity = new MessageEntity(
                        "系统",
                        participant + "加入直播间"
                );
                messageEntitiesList.add(messageEntity);
                chatRoomMessageAdapter.notifyDataSetChanged();
                dataBinding.liveChatRoomRv.scrollToPosition(messageEntitiesList.size() - 1);

            });
        }

        @Override
        public void onMemberExited(String roomId, String roomName, String participant) {
            runOnUiThread(() -> {
                MessageEntity messageEntity = new MessageEntity(
                        "系统",
                        participant + "退出了直播间"
                );
                messageEntitiesList.add(messageEntity);
                chatRoomMessageAdapter.notifyDataSetChanged();
                dataBinding.liveChatRoomRv.scrollToPosition(messageEntitiesList.size() - 1);

            });
        }

        @Override
        public void onRemovedFromChatRoom(int reason, String roomId, String roomName, String participant) {

        }

        @Override
        public void onMuteListAdded(String chatRoomId, List<String> mutes, long expireTime) {

        }

        @Override
        public void onMuteListRemoved(String chatRoomId, List<String> mutes) {

        }

        @Override
        public void onWhiteListAdded(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onWhiteListRemoved(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onAllMemberMuteStateChanged(String chatRoomId, boolean isMuted) {

        }

        @Override
        public void onAdminAdded(String chatRoomId, String admin) {

        }

        @Override
        public void onAdminRemoved(String chatRoomId, String admin) {

        }

        @Override
        public void onOwnerChanged(String chatRoomId, String newOwner, String oldOwner) {

        }

        @Override
        public void onAnnouncementChanged(String chatRoomId, String announcement) {

        }
    };

    //聊天消息接收监听器
    private EMMessageListener emMessageListener = messages -> {
        runOnUiThread(() -> {
            for (int i = 0; i < messages.size(); i++) {
                MessageEntity messageEntity = new MessageEntity(
                        messages.get(i).getUserName(),
                        ((EMTextMessageBody) messages.get(i).getBody()).getMessage()
                );
                messageEntitiesList.add(messageEntity);
                chatRoomMessageAdapter.notifyDataSetChanged();
            }
        });
    };

    //发送礼物的方法
    private void sendGift() {
        //拿到用户余额
        //扣款逻辑(账号余额是否充足 -> 充足,余额足够->扣款,更新UI,更新数据库中的新余额)
        //发送礼物的时候,礼物不能为空,余额也不能为空
        if (giftBean == null || money == null) {
            ToastUtils.showLong("余额不足,或者请选择礼物再发送");
            return;
        }

        //判断余额小于礼物价格,余额不足
        if (money.money < giftBean.getPrice()) {
            ToastUtils.showLong("余额不足,请充值");
            return;
        }

        //准备更新余额.新的余额等于当前余额减去礼物价格
        float newMoney = money.money - giftBean.getPrice();
        dataBinding.liveUserMoneyTv.setText("余额:" + newMoney + "抖币");

        //给余额赋值
        money.money = newMoney;
        AppDBUtils.getInstance().getMoneyDao().updateMoney(money);


        //构建一个ImageView承载动画
        ImageView giftAnimView = new ImageView(this);
        //直接new出的view,没有属性,也没有宽高,需要设置一个宽高才能显示出来
        //宽高不能直接给View设置,需要通过Layout的Params来设置
        //需要展示在那个Layout上,就创建哪种Layout的Params
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(200, 200);
        giftAnimView.setLayoutParams(params);

        //将构建好的ImageView添加到布局上
        dataBinding.liveRootCl.addView(giftAnimView);
        ImageLoader.getInstance().loadImage(this, giftBean.getGiftpath(), giftAnimView);

        //展示动画
        //获取rootLayout的宽高
        int screenWidth = dataBinding.liveRootCl.getMeasuredWidth();
        int screenHeight = dataBinding.liveRootCl.getMeasuredHeight();

        ObjectAnimator translateY = ObjectAnimator.ofFloat(giftAnimView, "translationY", screenHeight,
                screenHeight / 3 * 2, screenHeight / 2);
        ObjectAnimator translateX = ObjectAnimator.ofFloat(giftAnimView, "translationX", screenWidth / 2,
                screenWidth / 3 * 2, screenWidth / 2, screenWidth / 3, screenWidth / 2);

        ObjectAnimator rotation = ObjectAnimator.ofFloat(giftAnimView, "rotation", 0, 720);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(giftAnimView, "scaleX", 1, 2);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(giftAnimView, "scaleY", 1, 2);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(giftAnimView, "alpha", 0.1f, 0.5f, 1.0f, 0.5f, 0.1f);

        AnimatorSet set = new AnimatorSet();
        set.setDuration(3000);
        set.setInterpolator(new AccelerateDecelerateInterpolator());
        set.playTogether(translateX, translateY, rotation, alpha, scaleX, scaleY);

        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //动画结束时移除掉礼物imageView
                dataBinding.liveRootCl.removeView(giftAnimView);
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                //动画开始时,关闭礼物列表
                dataBinding.liveGiftLayoutCl.setVisibility(View.GONE);
            }
        });
        set.start();
    }

    private void sendDanmu() {
        //获取弹幕内容
        String danmuString = dataBinding.liveDanmuInputEt.getText().toString();
        if (TextUtils.isEmpty(danmuString)) {
            ToastUtils.showLong("请输入弹幕内容");
            return;
        }

        //清理弹幕
        dataBinding.liveDanmakuView.clear();
        dataBinding.liveDanmakuView.removeAllDanmakus(true);

        //创建弹幕实体
        BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);//设置弹幕方向
        danmaku.text = danmuString;//弹幕内容
        danmaku.textSize = 30;//弹幕大小
        danmaku.textColor = Color.WHITE;
        danmaku.padding = 10;//内边距
        danmaku.setTime(800);

        //添加弹幕到弹幕的view中
        dataBinding.liveDanmakuView.addDanmaku(danmaku);
        dataBinding.liveDanmakuView.start();


        //清空输入框
        dataBinding.liveDanmuInputEt.postDelayed(() -> {
            dataBinding.liveDanmuInputEt.setText("");
            dataBinding.liveDanmuInputLl.setVisibility(View.GONE);
        }, 300);

    }

    //初始化需要一个弹幕的上下文
    private DanmakuContext danmakuContext;

    private void initDanmuView() {
        //1.清理弹幕的缓存
        dataBinding.liveDanmakuView.enableDanmakuDrawingCache(false);
        dataBinding.liveDanmakuView.clear();
        dataBinding.liveDanmakuView.removeAllDanmakus(true);

        //2.准备弹幕的上下文
        danmakuContext = DanmakuContext.create();

        //3.准备弹幕
        dataBinding.liveDanmakuView.prepare(new BaseDanmakuParser() {
            @Override
            protected IDanmakus parse() {
                return new Danmakus();
            }
        }, danmakuContext);
    }

    @Override
    protected Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_live;
    }
}